/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package arc;

import com.jme3.app.SimpleApplication;
import com.jme3.input.FlyByCamera;
import com.jme3.niftygui.NiftyJmeDisplay;
import com.jme3.system.AppSettings;
import com.jme3.system.JmeContext;
import de.lessvoid.nifty.Nifty;
import de.lessvoid.nifty.controls.Label;
import de.lessvoid.nifty.controls.label.LabelControl;
import de.lessvoid.nifty.screen.Screen;
import de.lessvoid.nifty.screen.ScreenController;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFrame;

/**
 *
 * @author Adam
 */

public class Main extends SimpleApplication {
    ArcServer serverApp;
    ArrayList<ArcClient> clientList = new ArrayList<ArcClient>();
    private Nifty nifty;
    
    public static void main(String[] args) {
        Main app = new Main();
        app.start(JmeContext.Type.Headless);
        
        JFrame frame = new JFrame("Arc Network Manager");
        frame.setSize(100, 100);
        frame.addWindowListener(new ExitListener(app));
        frame.setVisible(true);
    }
    
    @Override
    public void simpleInitApp() {
         startServer();
         addClient(new ArcClient());
    }
    
    @Override
    public void simpleUpdate(float tpf)
    {
    }
    
    @Override
    public void stop()
    {
        if(serverApp != null) serverApp.stop();
        removeClients();
        super.stop();
    }
    
    public void startServer()
    {
        if(serverApp != null) return;
        serverApp = new ArcServer();
        serverApp.start(JmeContext.Type.Headless);
        AppSettings serverSettings = new AppSettings(true);
        serverSettings.setFrameRate(1);
        serverApp.setSettings(settings);
    }
    
    public void addClient(ArcClient client)
    {
        if(clientList.contains(client)) return;
        clientList.add(client);
        client.start();
    }
    
    public void removeClients()
    {
        for(ArcClient client : clientList)
        {
            client.close("Server manager is closing the connection");
        }
        clientList.clear();
    }
    
    public void stopServer()
    {
        if(serverApp == null) return;
        serverApp.stop();
        serverApp = null;
    }
    
    @Override
    public void destroy()
    {
        removeClients();
        stopServer();
        super.destroy();
        
        System.out.println("[Manager]\tDestroyed");
    }
}
